import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)
// 导入页面组件
// import login from '@/views/login'
// import layout from '@/views/layout'
// import home from '@/views/home'
// import my from '@/views/my'
// import qa from '@/views/qa'
// import video from '@/views/video'
// import search from '@/views/search'
// import article from '@/views/article'
// import userProfile from '@/views/user-profile'

const routes = [
  {
    path:'/login',
    component:()=> import('@/views/login')
  },
  {
    path:'/',
    component:()=> import('@/views/layout'),
    children:[
      {
        path:'',
        component:()=> import('@/views/home')
      },
      {
        path:'qa',
        component:()=> import('@/views/qa')
      },
      {
        path:'my',
        component:()=> import('@/views/my')
      },
      {
        path:'video',
        component:()=> import('@/views/video')
      }
    ]
  },
  {
    path:'/search',
    component:()=> import('@/views/search')
  },
  {
    path: '/user/profile',
    name: 'user-profile',
    component:()=> import('@/views/user-profile')
  },
  {
    path:'/article/:articleId',
    name:'article',  // 命名路由，本质就是该路由映射的名称
    props:true,  // 会将动态路由数据，注入到页面组件的props中去
    component:()=> import('@/views/article')
  },
]

const router = new VueRouter({
  routes
})

// 导航守卫函数
router.beforeEach((to,from,next)=>{
  // 要去的页面是否需要登录呢？
  let authList = ['/user/profile']
  if(authList.includes(to.path)){
    // ==>A、需要登录，判断是否登录了
    if(store.getters.token){
      // =====> 1. 登录了，放行
      next()
    }else{
      // =====> 2. 未登录了，跳转到登录界面
      next('/login?to='+to.path)
    }
  }else{
    // ==>B、不需要登录，直接放行
    next()
  }
})

export default router
